using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Security;

namespace ITProf.QuickMailer
{
    internal class Mailer
    {
        public string SmtpServerHost { get; set; }
        public int SmtpServerPort { get; set; }
        public bool UseSSL { get; set; }
        public SecureString UserName { get; set; }
        public SecureString UserPassword { get; set; }

        public void Send(string subject, string text, string emailFrom, string nameFrom, IList<string> emailTo,
                         string replyTo,
                         MailPriority priority, params string[] attachements)
        {
            var msg = new MailMessage();

            msg.ReplyTo = new MailAddress(replyTo);

            // Your mail address and display name.
            // This what will appear on the From field.
            // If you used another credentials to access
            // the SMTP server, the mail message would be
            // sent from the mail specified in the From
            // field on behalf of the real sender.
            msg.From =
                new MailAddress(emailFrom, nameFrom);

            // To addresses
            if (emailTo.Count == 1)
            {
                msg.To.Add(new MailAddress(emailTo[0]));
            }
            else
            {
                for (int i = 0; i < emailTo.Count; i++)
                {
                    msg.Bcc.Add(new MailAddress(emailTo[i]));
                }
            }

            // You can specify CC and BCC addresses also

            // Set to high priority
            msg.Priority = priority;

            msg.Subject = subject;

            // You can specify a plain text or HTML contents
            msg.Body = text;
            // In order for the mail client to interpret message
            // body correctly, we mark the body as HTML
            // because we set the body to HTML contents.
            msg.IsBodyHtml = false;

            if (attachements != null)
            {
                foreach (string attachement in attachements)
                {
                    // Attaching some data
                    msg.Attachments.Add(new Attachment(attachement));
                }
            }

            // Connecting to the server and configuring it
            var client = new SmtpClient();
            client.Host = SmtpServerHost;
            client.Port = SmtpServerPort;
            client.EnableSsl = UseSSL;
            // The server requires user's credentials
            // not the default credentials
            client.UseDefaultCredentials = false;
            // Provide your credentials
            client.Credentials =
                new NetworkCredential(
                    SecureHelper.ConvertToString(UserName), SecureHelper.ConvertToString(UserPassword));

            // Use SendAsync to send the message asynchronously
            client.Timeout = 45000;
            client.Send(msg);
        }
    }
}